package com.glela;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LogInterceptors implements HandlerInterceptor {
	private static Logger			LOGGER					= LoggerFactory.getLogger(LogInterceptors.class);
	private static final String		USER_TOKEN				= "userToken";
	private NamedThreadLocal<Long>	startTimeThreadLocal	= new NamedThreadLocal<Long>("StopWatch-StartTime");

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		LOGGER.error("请求地址 {} {}://{}:{}{} 参数：{} token:{}", new Object[] { request.getMethod(), request.getScheme(), request.getLocalAddr(), request.getServerPort(), request.getRequestURI(), IOUtils.toString(request.getInputStream()), request.getHeader(USER_TOKEN) });
		startTimeThreadLocal.set(System.currentTimeMillis());//线程绑定变量（该数据只有当前请求的线程可见）
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
		long endTime = System.currentTimeMillis();//2、结束时间  
		long beginTime = startTimeThreadLocal.get();//得到线程绑定的局部变量（开始时间）  
		long consumeTime = endTime - beginTime;//3、消耗的时间  
		if (consumeTime > 0) {//此处认为处理时间超过500毫秒的请求为慢请求  
			//TODO 记录到日志文件  
			LOGGER.error("响应地址 {} {}://{}:{}{}耗时：{}", new Object[] { request.getMethod(), request.getScheme(), request.getLocalAddr(), request.getServerPort(), request.getRequestURI(), consumeTime });
		}
	}
}